package demo.preference.com.bluetoothdemo;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.hlife.com.bluetooth20_connect.lib.BluetoothService;
import cn.hlife.com.bluetooth20_connect.util.LogUtils;
import demo.preference.com.bluetoothdemo.utils.DateUtils;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;
import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;

public class MainActivity extends AppCompatActivity {
    String TAG = MainActivity.class.getSimpleName();
    ProgressBar progressBar;
    ListView listView;
    private final static UUID UUID_NOTIFY =
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
    private final static UUID UUID_SERVICE =
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
    ListViewAdapter listViewAdapter;
    int PERMISSION_REQUEST_COARSE_LOCATION = 101;
    Dialog dialog;
    DialogUtils dialogUtils;
     String MAC;
    TextView  showText;
    String imei;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        showText=(TextView)findViewById(R.id.show_text);
        listViewAdapter = new ListViewAdapter();
        listView.setAdapter(listViewAdapter);
        if (!ClientManager.getClient().isBluetoothOpened()) {
            ClientManager.getClient().openBluetooth();
        }
        findViewById(R.id.search_bluetooth).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchBluetooth();
            }
        });
        findViewById(R.id.stop_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClientManager.getClient().stopSearch();
            }
        });
        findViewById(R.id.upload_bluetooth_list).setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                DateUtils.currentTime();
                DateUtils.getDay(System.currentTimeMillis());
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
        dialogUtils = new DialogUtils();
        findViewById(R.id.test1_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                write(new  byte[]{0x44,0x4E,0x11});
            }
        });
        findViewById(R.id.test2_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                write(new  byte[]{0x55,0x46,0x10});
            }
        });

        findViewById(R.id.disconnect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClientManager.getClient().disconnect(MAC);
            }
        });
        findViewById(R.id.return_bluetooth2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent  intent=new Intent(MainActivity.this,Bluetooth2.class);
                startActivity(intent);
            }
        });
        imei= ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
    }


    private final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {

        @Override
        public void onConnectStatusChanged(String mac, int status) {
            if (status == STATUS_CONNECTED) {
                notifyResponse();
            } else if (status == STATUS_DISCONNECTED) {
                ClientManager.getClient().unnotify(MAC, UUID_NOTIFY, UUID_SERVICE, new BleUnnotifyResponse() {
                    @Override
                    public void onResponse(int code) {
                        if (code == REQUEST_SUCCESS) {

                        }
                    }
                });
                Toast.makeText(MainActivity.this, "连接断开", Toast.LENGTH_LONG).show();
                showText.post(new Runnable() {
                    @Override
                    public void run() {
                        showText.setText("");
                    }
                });
                Log.e(TAG, "连接断开");
            }
        }
    };

    public void searchBluetooth() {
        //判断是否有权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                Log.e(TAG, "申请权限");
                return;
            }

        } else {

            Log.e(TAG, "有权限");
            Toast.makeText(MainActivity.this, "有权限", Toast.LENGTH_LONG).show();

        }
        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
//                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                .build();

        ClientManager.getClient().search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                listViewAdapter.clean();
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                listViewAdapter.setDataArray(device);
                Log.e(TAG, "蓝牙名称：" + device.getName() + "蓝牙地址:" + device.getAddress());
            }

            @Override
            public void onSearchStopped() {
                progressBar.setVisibility(View.GONE);

            }

            @Override
            public void onSearchCanceled() {
                progressBar.setVisibility(View.GONE);

            }
        });

    }
    public  void notifyResponse(){
        ClientManager.getClient().notify(MAC, UUID_SERVICE, UUID_NOTIFY, new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
               final String  str=TransformDataUtils.toHex(value);
                showText.post(new Runnable() {
                    @Override
                    public void run() {
                        showText.setText(str);
                    }
                });
            }
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }
    public void write(byte []   bytes){
        ClientManager.getClient().write(MAC, UUID_SERVICE, UUID_NOTIFY, bytes, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                        Log.e(TAG,"写入数据");
                }
            }
        });
    }


    public class ListViewAdapter extends BaseAdapter {
        ArrayList<SearchResult> arrayList = new ArrayList<SearchResult>();

        public void setDataArray(SearchResult searchResult) {
            if (!arrayList.contains(searchResult)) {
                arrayList.add(searchResult);
            }
            notifyDataSetChanged();
        }

        public void clean() {
            arrayList.clear();
        }

        ;

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHodler viewHodler;
            if (convertView == null) {
                viewHodler = new ViewHodler();
                convertView = getLayoutInflater().inflate(R.layout.base_item, parent, false);
                viewHodler.name = (TextView) convertView.findViewById(R.id.name);
                viewHodler.mac = (TextView) convertView.findViewById(R.id.mac);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHodler) convertView.getTag();
            }
            viewHodler.name.setText(arrayList.get(position).getName());
            viewHodler.mac.setText(arrayList.get(position).getAddress());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    progressBar.setVisibility(View.VISIBLE);
                    MAC= arrayList.get(position).getAddress();
                    ClientManager.getClient().registerConnectStatusListener(MAC, mBleConnectStatusListener);

                    dialog = dialogUtils.createLucencyLoadingDialog(MainActivity.this);
                    ClientManager.getClient().connect(MAC, new BleConnectResponse() {
                        @Override
                        public void onResponse(int code, BleGattProfile profile) {
                            progressBar.setVisibility(View.GONE);
                            if (code == REQUEST_SUCCESS) {
                                dialog.dismiss();

                                Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();

                                Log.e(TAG, "连接成功");
                            }
                        }
                    });
                }
            });
            return convertView;
        }

        class ViewHodler {
            TextView name, mac;
        }
    }
}
